<template>
  <div class="product">
    <div v-if="!isAddShow" class="product_list">
      <div class="filter-container">
        <el-input v-model="listQuery.title"
                  placeholder="商品标题"
                  style="width: 100px;"
                  class="filter-item"
                  @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.importance"
                   placeholder="商品类型"
                   clearable style="width: 110px"
                   class="filter-item">
          <el-option v-for="item in importanceOptions"
                     :key="item"
                     :label="item"
                     :value="item" />
        </el-select>
        <el-select v-model="listQuery.type"
                   placeholder="Type"
                   clearable class="filter-item" style="width: 130px">
          <el-option v-for="item in calendarTypeOptions"
                     :key="item.key"
                     :label="item.display_name+'('+item.key+')'"
                     :value="item.key" />
        </el-select>
        <el-select v-model="listQuery.sort"
                   style="width: 140px"
                   class="filter-item" >
          <el-option v-for="item in sortOptions"
                     :key="item.key"
                     :label="item.label"
                     :value="item.key" />
        </el-select>
        <el-button v-waves class="filter-item"
                   type="primary"
                   icon="el-icon-search"
                   @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;"
                   type="primary"
                   icon="el-icon-edit"
                   @click="handleCreate">
          新增商品
        </el-button>
        <el-button v-waves :loading="downloadLoading"
                   class="filter-item"
                   type="primary"
                   icon="el-icon-download"
                   @click="handleDownload">
          导出
        </el-button>
        <el-button v-waves
                   :loading="downloadLoading"
                   class="filter-item"
                   type="primary"
                   icon="el-icon-upload2"
                   @click="">
          导入
        </el-button>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="商品名称" prop="productame"
                         sortable="custom" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.productame }}</span>
          </template>
        </el-table-column>

        <el-table-column label="商品价格" prop="originalPrice"
                         sortable="custom" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.originalPrice===0?scope.row.price:scope.row.originalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品图片" prop="picpath"
                         sortable="custom" align="center" width="180">
          <template slot-scope="scope">
            <!--scope.row.picpath===null?scope.row.picpath:scope.row.merchantsPics.merchantsPic-->
            <img  width="200" :src="scope.row.picpath" />
            <!--<span>{{ scope.row.picpath }}</span>-->
          </template>
        </el-table-column>
        <el-table-column label="库存" prop="inventory"
                         sortable="custom" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.inventory }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              修改
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDel(row)">
              删除
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDel(row)">
              上架
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDel(row)">
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination small v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.page"
                  :limit.sync="listQuery.limit"
                  @pagination="getList" />

      <el-dialog :title="textMap[dialogStatus]"
                 :visible.sync="dialogFormVisible">
        <el-form ref="dataForm"
                 :model="temp"
                 label-position="left" label-width="130px" style="width: 400px; margin-left:50px;">
          <el-form-item label="商品名称" prop="productame">
            <el-input v-model="temp.productame" />
          </el-form-item>
          <el-form-item label="商品现价" prop="originalPrice">
            <el-input v-model="temp.originalPrice" />
          </el-form-item>
          <el-form-item label="商品原价" prop="price">
            <el-input v-model="temp.price" />
          </el-form-item>
          <el-form-item label="商品图片" prop="picpath">
            <el-input v-model="temp.picpath" />
          </el-form-item>
          <el-form-item label="库存" prop="inventory">
            <el-input v-model="temp.inventory" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary"
                     @click="dialogStatus==='create'?createData():updateData()">
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
    <div v-else class="addProduct">
      <h3>商品主图</h3>
      <div class="main_pic">
        <el-upload multiple
                   action="http://localhost:8080/upload"
                   list-type="picture-card"
                   :on-preview="handlePictureCardPreview"
                   :on-success="handleUploadSuccess"
                   :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </div>
      <h3>商品名称</h3>
      <el-input
        placeholder="请输入商品名称"
        v-model="temp.productame"
        clearable style="width: 25%">
      </el-input>
      <h3>商品原价(￥)</h3>
      <el-input-number v-model="temp.price" :precision="2"
                       :step="0.1" :min="0"></el-input-number>
      <h3>商品现价(￥)</h3>
      <el-input-number v-model="temp.originalPrice" :precision="2"
                       :step="0.1" :min="0"></el-input-number>
      <h3>商品库存</h3>
      <el-input-number v-model="temp.inventory" :precision="0"
                       :step="1" :min="0"></el-input-number>

      <h3>商家名称</h3>
      <el-autocomplete
        popper-class="my-autocomplete"
        v-model="shangjiaName"
        :fetch-suggestions="querySearch2"
        placeholder="请输入..."
        @select="handleSelect">
        <i
          class="el-icon-edit el-input__icon"
          slot="suffix"
          @click="handleIconClick">
        </i>
        <template slot-scope="{ item }">
          <!--<div class="name">{{ item.id }}</div>-->
          <span class="addr">{{ item.name }}</span>
        </template>
      </el-autocomplete>

      <h3>商品分类</h3>
      <el-autocomplete
        popper-class="my-autocomplete"
        v-model="className"
        :fetch-suggestions="querySearch3"
        placeholder="请输入..."
        @select="handleSelects">
        <i
          class="el-icon-edit el-input__icon"
          slot="suffix"
          @click="handleIconClick">
        </i>
        <template slot-scope="{ item }">
          <!--<div class="name">{{ item.value }}</div>-->
          <span class="addr">{{ item.cname }}</span>
        </template>
      </el-autocomplete>

      <h3>商品详情</h3>
      <vue-ueditor-wrap
        v-model="temp.datail"
        :config="myConfig"></vue-ueditor-wrap>
      <hr />
      <el-button :loading="saving" type="success" @click="saveGoods">保存</el-button>
      <el-button type="info">取消</el-button>
    </div>
  </div>
</template>

<script>
  import $ from 'jquery';
  import ajax from '@/utils/baseurl'
  import Pagination from '@/components/Pagination'
  import waves from '@/directive/waves'
  import VueUeditorWrap from 'vue-ueditor-wrap'

  var p;
  var oldtemp={
    classification:{},
    productame :'',
    originalPrice:89.90,
    price:100.00,
    picpath:'',
    inventory:100,
    buyNumber:'',
    merchantsPics:[],
    datail:'',
    merchants:{}
  }
  export default {
    name: 'Goods',
    components: { Pagination,VueUeditorWrap },
    directives: { waves },
    data() {
      return {
        saving:false,
        myConfig:{
          autoHeightEnabled: false,
          initialFrameHeight: 240,
          initialFrameWidth: '100%',
          serverUrl: 'http://localhost:8080/upload',
          //serverUrl : 'http://35.201.165.105:8000/controller.php',
          UEDITOR_HOME_URL:'/UEditor/'
        },
        dialogImageUrl: '',
        dialogVisible: false,
        isAddShow:false,
        temp: {
          classification:{},
          productame :'',
          originalPrice:89.90,
          price:100.00,
          picpath:'',
          inventory:100,
          buyNumber:'',
          merchantsPics:[],
          datail:'',
          merchants:{}
        },
        restaurants: [],
        shangjias:[],
        classifications:[],
        shangjiaName:'',
        className:'',
        state: '',
        textMap: {
          update: '修改',
          create: '新增'
        },
        listQuery: {
          page: 1,
          limit: 10,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        dialogFormVisible:false,
        dialogStatus: '',
        downloadLoading:false,
        total: 0,
        tableKey:0,
        listLoading:false,
        list:null,
        importanceOptions: ['特价', '售罄', '正常'],
        calendarTypeOptions: [
          { key: 'CN', display_name: 'China' },
          { key: 'US', display_name: 'USA' },
          { key: 'JP', display_name: 'Japan' },
          { key: 'EU', display_name: 'Eurozone' }
        ],
        sortOptions: [{ label: 'ID 升序', key: '+id' },
          { label: 'ID 降序', key: '-id' }]
      }

    },
    created() {
      p=this;
      this.getList();
      this.getShangjia();
      // this.getClassifications();
      this.getFenlei();
    },
    mounted() {
      this.restaurants = this.loadAll();
    },
    methods:{
      handleUploadSuccess(response, file, fileList){
        for(var i=0;i<fileList.length;i++){
          // console.log(JSON.stringify(fileList[i].response)+">>>>>");
          var f=fileList[i].response.title;
          this.temp.merchantsPics.push(
            {merchantsPic:f}
          )
        }
        //  console.log(fileList);
        // console.log(this.temp.merchantsPics);
      },
      saveGoods(){
        this.saving=true;
        var p=this;
        ajax("/goodsAdd",this.temp,function(data){
          if(data==1){
            p.$message({
              message: '添加成功！',
              type: 'success'
            });
          }
          p.isAddShow=false;
          p.saving=false;
        });


      },
      querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        cb(results);
      },
      querySearch2(queryString, cb) {
        var shangjias = this.shangjias;
        var results = queryString ?
          shangjias.filter(this.createFilter(queryString)) : shangjias;
        cb(results);
      },
      querySearch3(queryString, cb) {
        var classifications = this.classifications;
        // console.log(this.classifications);
        var results = queryString ?
          classifications.filter(this.createFilter1(queryString)) : classifications;
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      createFilter1(queryString) {
        return (restaurant) => {
          console.log(restaurant.cname);
          return (restaurant.cname.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      loadAll() {
        return [
          { "value": "CoCo都可(北新泾店）", "address": "上海市长宁区仙霞西路" },
          { "value": "快乐柠檬（神州智慧店）", "address": "上海市长宁区天山西路567号1层R117号店铺" },
          { "value": "Merci Paul cafe", "address": "上海市普陀区光复西路丹巴路28弄6号楼819" },
          { "value": "猫山王（西郊百联店）", "address": "上海市长宁区仙霞西路88号第一层G05-F01-1-306" },
          { "value": "南拳妈妈龙虾盖浇饭", "address": "普陀区金沙江路1699号鑫乐惠美食广场A13" }
        ];
      },
      handleSelect(item) {
        // console.log(item);
        this.shangjiaName=item.name;
        // console.log(this.temp);
        this.temp.merchants=item;
      },
      handleSelects(item) {
        // console.log(item);
        this.className=item.cname;
        // console.log(this.temp);
        this.temp.classification=item;
      },
      handleIconClick(ev) {
        console.log(ev);
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      updateData(){
        this.createData();
        this.getList();
      },
      resetTemp() {
        this.temp = {
          productname :'',
          originalPrice:'',
          price:'',
          picpath:'',
          inventory:'',
          buyNumber:'',
          name:''
        }
      },
      handleUpdate(row){
        // this.temp = Object.assign({}, row);
        // this.dialogStatus = 'update';
        // this.dialogFormVisible = true;
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].clearValidate()//清除验证
        // })

      },
      handleDel(row){
        var p = this;
        this.$confirm('确认删除吗? 是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax("/goodsDel",{"id": row.id },function(data){
            if(data){
              p.getList();
              p.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      sortChange() {

      },
      handleFilter(){

      },
      createData(){

      },
      handleCreate(){
        this.isAddShow=true;
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
      },
      handleDownload(){

      },
      getShangjia(){
        var p=this;
        ajax("/findmerchants",{},function(data){
          // console.log(data);
          p.shangjias=data;
        })
      },
      getFenlei(){
        var p=this;
        ajax("/findclassification",{},function(data){
          // console.log(1);
          // console.log(data);
          p. classifications=data;

        })
      },
      getList(){
        let p = this;
        this.listLoading = true;
        // console.log(this.listQuery);
        ajax("/findAll",this.listQuery,function(data){
          data = JSON.parse(data);
          // console.log(data);
          p.list=data.page.list;
          p.total=data.page.totalCount;
          p.listLoading=false;
        })
      },
    }
  }
</script>
<style scoped>

  h3{
    margin: 10px auto;
  }
  .addProduct{
    padding: 30px;
  }
  /*.my-autocomplete {*/
  /*li {*/
  /*line-height: normal;*/
  /*padding: 7px;*/

  /*.name {*/
  /*text-overflow: ellipsis;*/
  /*overflow: hidden;*/
  /*}*/
  /*.addr {*/
  /*font-size: 12px;*/
  /*color: #b4b4b4;*/
  /*}*/

  /*.highlighted .addr {*/
  /*color: #ddd;*/
  /*}*/
  /*}*/
  /*}*/

</style>













